<template>
  <div class="comment-list">
    <van-list :immediate-check="false" :error.sync="error" error-text="请求失败，点击重新加载" v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <CommentItem @replay-click="$emit('replay-click',$event)" :comment="item" v-for="(item, index) in list2" :key="index"></CommentItem>
    </van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comment.js'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list2: {
      tyoe: Array,
      default: () => []
    },
    type: {
      type: String,
      validator(value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data() {
    return {
      list: this.list2,
      loading: false,
      error: false,
      finished: false,
      offset: null, // 获取下一页数据的标记
      limit: 10
    }
  },
  created() {
    // 当手动初始onload的时候 它不会自动开始初始的loading  所以就要手动来开启
    this.loading = true
    this.onLoad()
  },
  methods: {
    async onLoad() {
      try {
        // 1. 请求获取数据
        const { data } = await getComments({
          type: this.type, // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.source.toString(), // 源id，文章id或评论id
          offset: this.offset,
          limit: this.limit
        })
        // console.log(data)
        // 2将数据添加到列表中
        const { results } = data.data
        this.list = [...this.list, ...results]
        // 把获取的评论数量传递给父组件
        this.$emit('onload-success', data.data)
        // 3完了之后将loading设置为false
        this.loading = false
        // 4判断是否还有数据
        if (results.length) {
          // 还有的话就获取下一页页码值
          this.offset = data.data.last_id
        } else {
          // 如果没有就将状态设置为结束
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
